import { message, Result } from 'antd';
import { useEffect, useState } from 'react';
import useOAuthSession from '@/pages/oidc/utils/useOAuthSession';
import useOAuthConfig from '@/pages/oidc/utils/useOAuthConfig';
import request from 'umi-request';
import { useModel } from '@@/plugin-model/useModel';

export default function LoggedIn(props: any) {
  const { setLoginUser } = useModel('loginUser');
  const [info, setInfo] = useState('登录成功，进入系统中...');

  useEffect(() => {
    const session = useOAuthSession();
    if (session.state !== props.location.query.state) {
      message.error('登录错误，STATE不匹配');
      setInfo('登录错误，STATE不匹配');
      return;
    }

    useOAuthConfig()
      .then((config) => {
        const params = [
          'grant_type=authorization_code',
          'redirect_uri=' + encodeURIComponent(config.redirectUri),
          'client_id=' + config.clientId,
          'code=' + props.location.query.code,
          'code_verifier=' + session.codeVerifier,
        ];

        request
          .post(config.oidcConfig.token_endpoint, {
            headers: {
              'Content-type': 'application/x-www-form-urlencoded',
            },
            data: params.join('&'),
          })
          .then((oidc) => {
            request
              .post('/api/resources/oauth/token', { data: oidc.id_token })
              .then((token) => {
                sessionStorage.setItem('OAuthIdToken', oidc.id_token);
                sessionStorage.setItem('Authorization', token.token);
                sessionStorage.setItem('LoginUser', JSON.stringify(token));
                setLoginUser(token);
                props.history.push('/');
              })
              .catch((err) => {
                message.error('更换TOKEN错误');
                throw err;
              });
          })
          .catch((err) => {
            message.error('获取TOKEN错误');
            throw err;
          });
      })
      .catch((err) => {
        message.error('获取登录信息错误');
      });
  }, []);

  return <Result title={info} />;
}
